﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Xml;
using System.Threading;
using System.Windows.Forms;

namespace pardusshipcalc
{
    class updateCheck
    {
        bool quiet;
        BackgroundWorker bgWorker;
        public updateCheck(bool Q)
        {
            quiet = Q;
            bgWorker = new BackgroundWorker();
            bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
            bgWorker.WorkerSupportsCancellation = true;


            bgWorker.RunWorkerAsync();        
        }

        private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            checkUpdates();
            bgWorker.CancelAsync();
        }

        private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Error != null) && (quiet != true))
            {
                MessageBox.Show(e.Error.Message);
            }
        }

        private void checkUpdates()
        {
            bool updateFailed = false;
            Version newVersion = null;
            string url = "http://www.drifter.herbal-jazz.net/tame/tsc.php";
            //string dev_url = "http://www.drifter.herbal-jazz.net/tame_dev/";

            XmlTextReader reader;
            try
            {
                string xmlURL = "http://www.drifter.herbal-jazz.net/tame/app_version.xml";
                reader = new XmlTextReader(xmlURL);
                reader.MoveToContent();
                // internal - as the XmlTextReader moves only
                // forward, we save current xml element name
                // in elementName variable. When we parse a
                // text node, we refer to elementName to check
                // what was the node name
                string elementName = "";
                // we check if the xml starts with a proper
                // "update_tame" element node
                if ((reader.NodeType == XmlNodeType.Element) &&
                    (reader.Name == "update_tame"))
                {
                    while (reader.Read())
                    {
                        // when we find an element node,
                        // we remember its name
                        if (reader.NodeType == XmlNodeType.Element)
                            elementName = reader.Name;
                        else
                        {
                            // for text nodes...
                            if ((reader.NodeType == XmlNodeType.Text) &&
                                (reader.HasValue))
                            {
                                // we check what the name of the node was
                                switch (elementName)
                                {
                                    case "version":
                                        // thats why we keep the version info
                                        // in xxx.xxx.xxx.xxx format
                                        // the Version class does the
                                        // parsing for us
                                        newVersion = new Version(reader.Value);
                                        break;
                                    case "url":
                                        url = reader.Value;
                                        break;
                                }
                            }
                        }
                    }
                }
                reader.Close();
            }

            catch (Exception)
            {
                //if (quiet != true)
                {
                    MessageBox.Show("Error Retrieving Update Info File!\n" + Environment.NewLine + "Check Your network connection and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                updateFailed = true;
            }

            if (updateFailed != true)
            {
                // get the running version
                Version curVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

                // compare the versions
                if (curVersion.CompareTo(newVersion) < 0)
                {
                    // ask the user if he would like
                    // to download the new version
                    DialogResult updateDialogResult = MessageBox.Show(string.Format("Update Found." + Environment.NewLine + "" + Environment.NewLine + "Your Version: {0}" + Environment.NewLine + "Server Version: {1}" + Environment.NewLine + "" + Environment.NewLine + "Would you like to download this update?", curVersion, newVersion), "Update Found!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (updateDialogResult == DialogResult.Yes)
                    {
                        // navigate the default web
                        // browser to our app
                        // homepage (the url
                        // comes from the xml content)
                        System.Diagnostics.Process.Start(url);
                    }

                }
                else
                {
                    if (quiet != true)
                    {
                        MessageBox.Show("No Updates Available", "No Updates", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            return;
        }
    }
}
